﻿#region
using System;
using System.Data;
using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using System.IO.Compression;
using ZhongLangDB;
#endregion

namespace ZHONGLANGWEBUI
{
    public partial class TT_BasePageList : TT_BasePage
    {
        #region 界面参数
        public string REQTITLE { get { return (Request["TITLE"] == null ? "" : Request["TITLE"].ToString()); } }
        public string REQFRMID { get { return (Request["FRMID"] == null ? "" : Request["FRMID"].ToString()); } }
        public int REQPAGECOUNT { get { return (Request["PAGECOUNT"] == null ? 25 : Convert.ToInt32(Request["PAGECOUNT"].ToString())); } }
        #endregion

        //=====================================================================================

        #region 列表排序
        protected void dgList_RowDataBound(object sender, GridViewRowEventArgs e) { }
        protected void dgList_Sorting(object sender, GridViewSortEventArgs e)
        {
            string strSortExpression = (ViewState["SortExpression"] == null ? "" : ViewState["SortExpression"].ToString());
            string strSortDirection = (ViewState["SortDirection"] == null ? "" : ViewState["SortDirection"].ToString());
            AddSortColumn(ref sender, e.SortExpression, ref strSortExpression, ref strSortDirection);
            ViewState.Add("SortExpression", strSortExpression);
            ViewState.Add("SortDirection", strSortDirection);
            pageBind();
        }
        protected string GetSortDirectiont(string strSortExpressionView, string strSortDirectionView)
        {
            string[] SortColumnAll = strSortExpressionView.Split('$');
            string[] DirectionAll = strSortDirectionView.Split('$');
            string strBack = "";
            for (int i = 0; i < SortColumnAll.Length; i++)
            {
                if (SortColumnAll[i] != "")
                {
                    strBack += (strBack == "" ? "" : ",") + SortColumnAll[i] + " " + DirectionAll[i];
                }
            }
            return strBack;
        }
        protected void AddSortColumn(ref object sender, string SortColumn, ref string SortExpressionView, ref string SortDirectionView)
        {
            if (SortExpressionView != "" && SortExpressionView == SortColumn && SortDirectionView == "ASC")
            {
                SortDirectionView = "DESC";
            }
            else
            {
                SortDirectionView = "ASC";
            }
            SortExpressionView = SortColumn;
            string strFIELDNAME = SortExpressionView, strFILEDDESC = SortDirectionView;

            for (int i = 0; i < ((GridView)sender).Columns.Count; i++)
            {
                string strHeadText = ((GridView)sender).Columns[i].HeaderText;
                strHeadText = strHeadText.Replace("↓", "").Replace("↑", "");
                if (((GridView)sender).Columns[i].SortExpression == strFIELDNAME)
                {
                    if (strFILEDDESC == "ASC") { strHeadText += "↑"; }
                    if (strFILEDDESC == "DESC") { strHeadText += "↓"; }
                }
                ((GridView)sender).Columns[i].HeaderText = strHeadText;
            }

        }
        #endregion
         
        #region 按钮操作
        protected void btn_Click(object sender, EventArgs e)
        {
            dgListBaseDo(((Button)(sender)).CommandName, ((Button)(sender)).CommandArgument);
        }
        protected void lbtn_Click(object sender, EventArgs e)
        {
            dgListBaseDo(((LinkButton)(sender)).CommandName, ((LinkButton)(sender)).CommandArgument);
        }
        protected void ibtn_Click(object sender, EventArgs e)
        {
            dgListBaseDo(((ImageButton)(sender)).CommandName, ((ImageButton)(sender)).CommandArgument);
        }
        protected void dgList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            dgListBaseDo(e.CommandName, e.CommandArgument.ToString());
        }
        protected void dgListDetail_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            dgListBaseDo(e.CommandName, e.CommandArgument.ToString());
        }
        
        protected void dgListBaseDo(string strCommandName, string strCommandArgument){  
            dgListDo(strCommandName, strCommandArgument);
        }
        protected void pageBaseBind() {
            Control tabCurrQuery = FindControl("tabQuery");
            Control tabCurrShow = FindControl("tabShow");
            Control tabCurrEdit = FindControl("tabEdit");
            
            //System.Web.UI.HtmlControls.HtmlTable
        }
        #endregion

        #region 基本方法 
        protected virtual void pageInit() { }
        protected virtual void pageBind() { }
        protected virtual void pageBindReset() { }
        protected virtual void dgListDo(string strCommandName, string strCommandArgument) { }

        #region 列表导出
        protected void proExpData(DataTable dt, GridView gv)
        {
            try
            {
                GridView gvOut = new GridView();
                gvOut.AutoGenerateColumns = false;
                gvOut.AllowPaging = false;
                gvOut.CssClass = gv.CssClass;
                gvOut.HeaderStyle.CssClass = gvOut.HeaderStyle.CssClass;
                gvOut.RowStyle.CssClass = gvOut.RowStyle.CssClass;
                gvOut.AlternatingRowStyle.CssClass = gvOut.AlternatingRowStyle.CssClass;
                for (int i = 0; i < gv.Columns.Count; i++)
                {
                    if (gv.Columns[i].GetType().Name == "BoundField" && gv.Columns[i].HeaderText != "")  //肯定是可以显示的数据帮定字段 BoundField HeaderText="" 可以规避隐藏列
                    {
                        BoundField bf = new BoundField();
                        bf.HeaderText = gv.Columns[i].HeaderText;
                        bf.DataField = ((BoundField)gv.Columns[i]).DataField;
                        gvOut.Columns.Add(bf);
                    }
                }
                gvOut.DataSource = dt;
                gvOut.DataBind();
                foreach (GridViewRow dr in gvOut.Rows)
                {
                    foreach (TableCell tc in dr.Cells)
                    {
                        tc.Attributes.Add("style", "vnd.ms-excel.numberformat:@");
                    }
                }
                Response.Clear();
                Response.Buffer = true;
                Response.Charset = "UFT-8"; // "GB2312";
                string expFileName = "attachment;filename=" + "XLS" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
                //if (rExecTypeDoc.Checked)
                //{
                //    expFileName = "attachment;filename=" + "DOC" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".doc";
                //}
                Response.AppendHeader("Content-Disposition", expFileName);
                Response.ContentType = "application/ms-excel";
                this.EnableViewState = false;
                System.IO.StringWriter swOut = new System.IO.StringWriter();
                HtmlTextWriter hTw = new HtmlTextWriter(swOut);
                gvOut.RenderControl(hTw);
                Response.Write(swOut.ToString());
                Response.End();
            }
            catch //(Exception ex)
            {
                Response.Write("<script>alert('导出数据失败');</script>");
            }
        }
        #endregion

        #region 数据压缩
        /// <summary>    
        /// 字节数组压缩    
        /// </summary>    
        /// <param name="strSource"></param>    
        /// <returns></returns>    
        public static byte[] Compress(byte[] data)
        {
            try
            {
                MemoryStream ms = new MemoryStream();
                GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true);
                zip.Write(data, 0, data.Length);
                zip.Close();
                byte[] buffer = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(buffer, 0, buffer.Length);
                ms.Close();
                return buffer;

            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
        /// <summary>    
        /// 字节数组解压缩    
        /// </summary>    
        /// <param name="strSource"></param>    
        /// <returns></returns>    
        public static byte[] Decompress(byte[] data)
        {
            try
            {
                MemoryStream ms = new MemoryStream(data);
                GZipStream zip = new GZipStream(ms, CompressionMode.Decompress, true);
                MemoryStream msreader = new MemoryStream();
                byte[] buffer = new byte[0x1000];
                while (true)
                {
                    int reader = zip.Read(buffer, 0, buffer.Length);
                    if (reader <= 0)
                    {
                        break;
                    }
                    msreader.Write(buffer, 0, reader);
                }
                zip.Close();
                ms.Close();
                msreader.Position = 0;
                buffer = msreader.ToArray();
                msreader.Close();
                return buffer;
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }


        /// 字符串压缩  
        public string CompressString(string str)
        {
            string compressString = "";
            byte[] compressBeforeByte = Encoding.GetEncoding("UTF-8").GetBytes(str);
            byte[] compressAfterByte = Compress(compressBeforeByte);
            compressString = Convert.ToBase64String(compressAfterByte);
            return compressString;
        }
        public string DecompressString(string str)
        {
            string compressString = "";
            byte[] compressBeforeByte = Convert.FromBase64String(str);
            byte[] compressAfterByte = Decompress(compressBeforeByte);
            compressString = Encoding.GetEncoding("UTF-8").GetString(compressAfterByte);
            return compressString;
        }

        public string EncodeString(string str) { return Server.UrlEncode(str); }
        public string DecodeString(string str) { return Server.UrlDecode(str); }
        #endregion

        #endregion

        //=====================================================================================
        #region 状态和下拉

        #endregion

        #region 表格处理

        #region 表格清除 
        protected void htbCLEAR(System.Web.UI.HtmlControls.HtmlTable tabEdit)
        {
            for (int i = 0; i < tabEdit.Rows.Count; i++)
            {
                for (int j = 0; j < tabEdit.Rows[i].Cells.Count; j++)
                {
                    if (tabEdit.Rows[i].Cells[j].Controls.Count > 0)
                    {
                        string strTT = tabEdit.Rows[i].Cells[j].Controls[0].ID;
                        if (strTT == null || strTT.Length < 4) { continue; }
                        string strType = strTT.Substring(0, 4);
                        string strName = strTT.Substring(4);
                        if (strType == "lblE"){((Label)(tabEdit.Rows[i].Cells[j].Controls[0])).Text = "";}
                        if (strType == "txtE"){((TextBox)(tabEdit.Rows[i].Cells[j].Controls[0])).Text = "";}
                        if (strType == "ddlE"){((DropDownList)(tabEdit.Rows[i].Cells[j].Controls[0])).SelectedIndex = 0; }
                    }
                }
            }
        }
        #endregion

        #region 表格绑定 
        public void htbBIND(DataTable dt, DataRow dr, System.Web.UI.HtmlControls.HtmlTable tabEdit)
        {
            for (int i = 0; i < tabEdit.Rows.Count - 1; i++)
            {
                for (int j = 0; j < tabEdit.Rows[i].Cells.Count; j++)
                {
                    for (int k = 0; k < tabEdit.Rows[i].Cells[j].Controls.Count; k++)
                    {
                        string strTT = tabEdit.Rows[i].Cells[j].Controls[k].ID;
                        if (strTT == null || strTT.Length < 4) { continue; }
                        string strType = strTT.Substring(0, 4);
                        string strName = strTT.Substring(4);
                        if (strType == "lblE"){if (dt.Columns.IndexOf(strName) >= 0){((Label)(tabEdit.Rows[i].Cells[j].Controls[k])).Text= dr[strName].ToString();}}
                        if (strType == "txtE"){if (dt.Columns.IndexOf(strName) >= 0){((TextBox)(tabEdit.Rows[i].Cells[j].Controls[k])).Text= dr[strName].ToString();}}
                        if (strType == "ddlE"){if (dt.Columns.IndexOf(strName) >= 0){DropDownList ddlObj = ((DropDownList)(tabEdit.Rows[i].Cells[j].Controls[k]));DDLBindValue(dr[strName].ToString(), ref ddlObj);}}
                        if (strType == "chkE"){if (dt.Columns.IndexOf(strName) >= 0){((CheckBox)(tabEdit.Rows[i].Cells[j].Controls[k])).Checked = (dr[strName].ToString() == "1"); } }
                        //if (strType == "chkE"){if (dt.Columns.IndexOf(strName) >= 0){CheckBoxList ddlObj = ((CheckBoxList)(tabEdit.Rows[i].Cells[j].Controls[k]));DDLBindValue(dr[strName].ToString(), ref ddlObj);}}
                    }
                }
            }
        }
        public void htbBIND(string strTextID, DataRow dr, System.Web.UI.HtmlControls.HtmlTable tabEdit){ ((TextBox)(tabEdit.FindControl(strTextID))).Text = dr[strTextID.Replace("txtE","")].ToString(); }
        #endregion

        #region 获取参数 
        public SortedList htbSDLISTQUERY(System.Web.UI.HtmlControls.HtmlTable tabEdit) { return htbSDLIST("Q", tabEdit); }
        public SortedList htbSDLISTSAVE(System.Web.UI.HtmlControls.HtmlTable tabEdit){return htbSDLIST("E", tabEdit);}
        public string htbSDLISTONE(string strTextID, System.Web.UI.HtmlControls.HtmlTable tabEdit) { return ((TextBox)(tabEdit.FindControl(strTextID))).Text ; } 
        public SortedList htbSDLIST(string strHead, System.Web.UI.HtmlControls.HtmlTable tabEdit)
        {
            SortedList SDList = new SortedList();
            for (int i = 0; i < tabEdit.Rows.Count; i++)
            {
                for (int j = 0; j < tabEdit.Rows[i].Cells.Count; j++)
                {
                    for (int k = 0; k < tabEdit.Rows[i].Cells[j].Controls.Count; k++)
                    {
                        string strTT = tabEdit.Rows[i].Cells[j].Controls[k].ID;
                        if (strTT == null || strTT.Length < 4) { continue; }
                        string strType = strTT.Substring(0, 4);
                        string strName = strTT.Substring(4);
                        if (strType == "txt" + strHead){ SDList["" + strName] = ((TextBox)(tabEdit.Rows[i].Cells[j].Controls[k])).Text.Split(' ')[0]; }
                        if (strType == "ddl" + strHead){ SDList["" + strName] = ((DropDownList)(tabEdit.Rows[i].Cells[j].Controls[k])).SelectedValue;}
                        if (strType == "chk" + strHead){ SDList["" + strName] = DDLBindValueCheckValueGet((CheckBoxList)(tabEdit.Rows[i].Cells[j].Controls[k]));}
                    }
                }
            } 
            return SDList;
        }
        #endregion

        #endregion

        //=====================================================================================
        
        #region getPIC
        public string proGETPIC(string strPICPath)
        {
            if (!System.IO.File.Exists(strPICPath)) { return ""; }
            FileStream fs = new FileStream(strPICPath, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fs);
            Byte[] FileByte = new Byte[(int)fs.Length];
            br.Read(FileByte, 0, (int)fs.Length);
            return Convert.ToBase64String(FileByte);
        }
        #endregion


        #region getCOM
        public static DataTable proGETCOM()
        {
            return DBPark.proGetDT(null, "SELECT COMID,COMCODE,COMNAME,COMCODE+' '+COMNAME COMCODENAME FROM TT_SYS_COM WHERE COMSTATE=1 ORDER BY COMNAME");
        }
        #endregion 

        #region getDept
        public static string PUB_DEPTSTR
        {
            get
            {
                string strBack = ""; DataTable dt = proGETDEPT();
                for (int i = 0; i < dt.Rows.Count; i++) { strBack += (i == 0 ? "" : ",") + dt.Rows[i]["DEPTID"].ToString() + "$" + dt.Rows[i]["DEPTCODE"].ToString() + " " + dt.Rows[i]["DEPTNAME"].ToString(); }
                return strBack;
            }
        }
        public static DataTable proGETDEPT() { return proGETDEPT(CURREMP.COMID,null); }
        public static DataTable proGETDEPT(string strCOMID,string strDEPTPRO)
        {
            strCOMID = DBPark.proPrameCheck(strCOMID); strDEPTPRO = DBPark.proPrameCheck(strDEPTPRO);
            return DBPark.proGetDT(null, "SELECT T.DEPTID,T.DEPTCODE,T.DEPTNAME,T.DEPTCODE+' '+"
                                                + (strCOMID != "" ? "" : " C.COMNAME+'>>' +")
                                                + (strDEPTPRO != "" ? "" : " CASE WHEN P.DEPTCODE IS NULL THEN '' ELSE P.DEPTNAME + '>>' END +") 
                                                +" T.DEPTNAME DEPTCODENAME "
                                         + "FROM TT_SYS_DEPT T"
                                   + " LEFT JOIN TT_SYS_DEPT P ON T.DEPTPRO = P.DEPTID "
                                   + (strCOMID != "" ? "" : " LEFT JOIN TT_SYS_COM  C ON T.COMID = C.COMID " ) 
                                        + " WHERE T.DEPTSTATE=1 " + (strCOMID == ""?"": " AND T.COMID=" + strCOMID) + (strDEPTPRO == "" ? "" : " AND T.DEPTPRO=" + strDEPTPRO)
                                        + " ORDER BY T.DEPTCODE"); 
        }
        public static DataTable proGETDEPTPRO() { return proGETDEPTPRO(CURREMP.COMID); }
        public static DataTable proGETDEPTPRO(string strCOMID)
        {
            strCOMID = DBPark.proPrameCheck(strCOMID);
            return DBPark.proGetDT(null, "SELECT T.DEPTID,T.DEPTCODE,T.DEPTNAME,T.DEPTCODE+' '+"
                                                + (strCOMID != "" ? "" : " C.COMNAME>> +") 
                                                + " T.DEPTNAME DEPTCODENAME "
                                         + "FROM TT_SYS_DEPT T" 
                                   + (strCOMID != "" ? "" : " LEFT JOIN TT_SYS_COM  C ON T.COMID = C.COMID ")
                                        + " WHERE T.DEPTSTATE=1 AND ISNULL(T.DEPTPRO,0) =0 " + (strCOMID == "" ? "" : " AND T.COMID=" + strCOMID) 
                                        + " ORDER BY T.DEPTCODE");
        }
        #endregion

        #region getUser
        public static string PUB_USERSTR(string strDEPTID)
        {
            string strBack = ""; DataTable dt = proGETUSER(strDEPTID);
            for (int i = 0; i < dt.Rows.Count; i++) { strBack += (i == 0 ? "" : ",") + dt.Rows[i]["USERID"].ToString() + "$" + dt.Rows[i]["USERLOGIN"].ToString() + " " + dt.Rows[i]["USERNAME"].ToString(); }
            return strBack;
        }

        public static DataTable proGETUSER(string strDeptID)
        {
            SortedList SDList = new SortedList();
            SDList["DEPTID"] = strDeptID;
            SDList["USERSTATE"] = 1; 
            return DBPark.proGetDT(SDList, "PROTT_SYS_USERQUERY");
        }
        #endregion
    }
}